import { useState, useEffect } from 'react'
import { useAuth } from '../contexts/AuthContext'
import { API_BASE_URL } from '../config'

interface Category {
  id: number
  name: string
  description: string
  icon?: string
  sort_order?: number
  created_at?: string
  promptCount?: number
}

interface Prompt {
  id: number
  title: string
  description: string
  prompt: string
  category: string
  aiModel: string
  author: string
  likes: number
  createdAt: string
}

export default function CategoryPage() {
  const { user } = useAuth()
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(null)
  const [categories, setCategories] = useState<Category[]>([])
  const [prompts, setPrompts] = useState<Prompt[]>([])
  const [loading, setLoading] = useState(true)
  const [promptsLoading, setPromptsLoading] = useState(false)
  const [error, setError] = useState('')
  const [promptsError, setPromptsError] = useState('')

  // 获取分类数据
  const fetchCategories = async () => {
    try {
      setLoading(true)
      setError('')
      
      const response = await fetch(`${API_BASE_URL}/api/v1/categories`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.data.categories) {
        // 转换API数据格式以匹配现有UI
        const transformedCategories = data.data.categories.map((category: any) => ({
          id: category.id,
          name: category.name,
          description: category.description,
          icon: category.icon,
          sort_order: category.sort_order,
          created_at: category.created_at,
          promptCount: 0 // 暂时设为0，后续可以通过其他接口获取
        }))
        
        setCategories(transformedCategories)
      } else {
        throw new Error('获取分类数据失败')
      }
    } catch (err) {
      console.error('获取分类失败:', err)
      setError(err instanceof Error ? err.message : '网络错误，请稍后重试')
      
      // 如果API调用失败，使用模拟数据作为降级方案
      setCategories(mockCategories)
    } finally {
      setLoading(false)
    }
  }

  // 获取分类下的提示词
  const fetchCategoryPrompts = async (categoryId: number) => {
    try {
      setPromptsLoading(true)
      setPromptsError('')
      
      const response = await fetch(`${API_BASE_URL}/api/v1/categories/${categoryId}/prompts`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 转换API数据格式以匹配现有UI
        const transformedPrompts = data.data.prompts?.map((prompt: any) => ({
          id: prompt.id,
          title: prompt.title,
          description: prompt.description,
          prompt: prompt.content,
          category: prompt.category?.name || '未分类',
          aiModel: prompt.ai_model?.name || '未知模型',
          author: prompt.user?.username || '匿名',
          likes: prompt.like_count || 0,
          createdAt: new Date(prompt.created_at).toLocaleDateString('zh-CN')
        })) || []
        
        setPrompts(transformedPrompts)
      } else {
        throw new Error(data.error || '获取提示词失败')
      }
    } catch (err) {
      console.error('获取分类提示词失败:', err)
      setPromptsError(err instanceof Error ? err.message : '网络错误，请稍后重试')
      
      // 如果API调用失败，使用模拟数据作为降级方案
      setPrompts(mockPrompts.filter(prompt => prompt.category === selectedCategory?.name))
    } finally {
      setPromptsLoading(false)
    }
  }

  // 获取所有提示词（当没有选中分类时）
  const fetchAllPrompts = async () => {
    try {
      setPromptsLoading(true)
      setPromptsError('')
      
      const response = await fetch(`${API_BASE_URL}/api/v1/prompts?page=1&limit=50`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 转换API数据格式以匹配现有UI
        const transformedPrompts = data.data.prompts?.map((prompt: any) => ({
          id: prompt.id,
          title: prompt.title,
          description: prompt.description,
          prompt: prompt.content,
          category: prompt.category?.name || '未分类',
          aiModel: prompt.ai_model?.name || '未知模型',
          author: prompt.user?.username || '匿名',
          likes: prompt.like_count || 0,
          createdAt: new Date(prompt.created_at).toLocaleDateString('zh-CN')
        })) || []
        
        setPrompts(transformedPrompts)
      } else {
        throw new Error(data.error || '获取提示词失败')
      }
    } catch (err) {
      console.error('获取所有提示词失败:', err)
      setPromptsError(err instanceof Error ? err.message : '网络错误，请稍后重试')
      
      // 如果API调用失败，使用模拟数据作为降级方案
      setPrompts(mockPrompts)
    } finally {
      setPromptsLoading(false)
    }
  }

  // 组件挂载时获取分类数据
  useEffect(() => {
    fetchCategories()
    fetchAllPrompts() // 初始加载所有提示词
  }, [])

  // 当选中分类改变时，获取对应的提示词
  useEffect(() => {
    if (selectedCategory) {
      fetchCategoryPrompts(selectedCategory.id)
    } else {
      fetchAllPrompts()
    }
  }, [selectedCategory])

  // 模拟分类数据（作为降级方案）
  const mockCategories: Category[] = [
    {
      id: 1,
      name: "风景",
      description: "自然风景、城市景观等",
      promptCount: 45
    }
  ]

  // 模拟提示词数据
  const mockPrompts: Prompt[] = [
    {
      id: 1,
      title: "科幻城市风景",
      description: "生成未来科幻城市的壮观景象",
      prompt: "A futuristic cyberpunk cityscape at night, neon lights reflecting on wet streets, flying cars, towering skyscrapers with holographic advertisements, highly detailed, 8k resolution",
      category: "风景",
      aiModel: "Midjourney",
      author: "张三",
      likes: 128,
      createdAt: "2024-01-15"
    }
  ]

  // 提示词数据现在通过API获取，不需要客户端过滤

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-gray-900">分类浏览</h1>
            {loading && <div className="text-sm text-gray-500">加载中...</div>}
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-8">
        {error && (
          <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
            <p className="text-red-600">{error}</p>
            <button 
              onClick={fetchCategories}
              className="mt-2 text-sm text-red-700 hover:text-red-900 underline"
            >
              重试
            </button>
          </div>
        )}
        <div className="flex gap-8">
          {/* 左侧分类列表 */}
          <div className="w-1/4">
            <div className="bg-white rounded-lg shadow-sm border">
              <div className="p-4 border-b">
                <h2 className="text-lg font-semibold text-gray-900">分类列表</h2>
              </div>
              <div className="p-2">
                <button
                  onClick={() => setSelectedCategory(null)}
                  className={`w-full text-left px-3 py-2 rounded-md transition-colors ${
                    !selectedCategory 
                      ? 'bg-blue-50 text-blue-700 border border-blue-200' 
                      : 'hover:bg-gray-50 text-gray-700'
                  }`}
                >
                  <div className="flex justify-between items-center">
                    <span>全部分类</span>
                    <span className="text-sm text-gray-500">{prompts.length}</span>
                  </div>
                </button>
                {categories.map((category) => (
                  <button
                    key={category.id}
                    onClick={() => setSelectedCategory(category)}
                    className={`w-full text-left px-3 py-2 rounded-md transition-colors mt-1 ${
                      selectedCategory?.id === category.id 
                        ? 'bg-blue-50 text-blue-700 border border-blue-200' 
                        : 'hover:bg-gray-50 text-gray-700'
                    }`}
                  >
                    <div className="flex justify-between items-center">
                      <div className="flex items-center gap-2">
                        {category.icon && <span className="text-lg">{category.icon}</span>}
                        <div>
                          <div className="font-medium">{category.name}</div>
                          <div className="text-sm text-gray-500">{category.description}</div>
                        </div>
                      </div>
                      <span className="text-sm text-gray-500">{category.promptCount || 0}</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* 右侧内容区域 */}
          <div className="flex-1">
            <div className="mb-6">
              <h2 className="text-xl font-semibold text-gray-900 mb-2">
                {selectedCategory ? selectedCategory.name : '全部分类'}
              </h2>
              <p className="text-gray-600">
                {selectedCategory 
                  ? selectedCategory.description 
                  : '浏览所有分类的优质提示词'}
              </p>
            </div>

            {promptsError && (
              <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-600">{promptsError}</p>
                <button 
                  onClick={() => selectedCategory ? fetchCategoryPrompts(selectedCategory.id) : fetchAllPrompts()}
                  className="mt-2 text-sm text-red-700 hover:text-red-900 underline"
                >
                  重试
                </button>
              </div>
            )}

            {promptsLoading && (
              <div className="text-center py-8">
                <div className="text-gray-500">加载提示词中...</div>
              </div>
            )}

            {/* 提示词网格 */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {prompts.map((prompt: Prompt) => (
                <div key={prompt.id} className="bg-white rounded-lg shadow-sm border hover:shadow-md transition-shadow">
                  <div className="p-6">
                    <div className="flex items-start justify-between mb-3">
                      <h3 className="text-lg font-semibold text-gray-900 line-clamp-1">
                        {prompt.title}
                      </h3>
                      <div className="flex items-center text-gray-500 text-sm">
                        <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
                        </svg>
                        {prompt.likes}
                      </div>
                    </div>
                    
                    <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                      {prompt.description}
                    </p>
                    
                    <div className="flex flex-wrap gap-2 mb-4">
                      <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                        {prompt.category}
                      </span>
                      <span className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                        {prompt.aiModel}
                      </span>
                    </div>
                    
                    <div className="flex items-center justify-between text-sm text-gray-500">
                      <span>by {prompt.author}</span>
                      <span>{prompt.createdAt}</span>
                    </div>
                    
                    <div className="mt-4 pt-4 border-t">
                      <button className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors text-sm">
                        查看详情
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {prompts.length === 0 && !promptsLoading && (
              <div className="text-center py-12">
                <div className="text-gray-500 text-lg mb-2">暂无提示词</div>
                <div className="text-gray-400 text-sm">该分类下还没有提示词，敬请期待</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}